use super::server::get_json_server_url;
use crate::models::app::AppItem;
use crate::models::category::Category;
use crate::utils::format::format_icon_url;
use crate::utils::UA;
use futures::future::join_all;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;

lazy_static! {
    static ref APPS_CACHE: Mutex<HashMap<String, Vec<AppItem>>> = Mutex::new(HashMap::new());
    static ref CATEGORIES_CACHE: Mutex<Option<Vec<Category>>> = Mutex::new(None);
}

#[tauri::command]
pub async fn get_category_apps(category_id: String) -> Result<Vec<AppItem>, String> {
    // 尝试从缓存中获取数据
    if let Some(cached_apps) = APPS_CACHE.lock().unwrap().get(&category_id) {
        return Ok(cached_apps.clone());
    }

    // 如果缓存中没有，从服务器获取数据
    let json_server_url = get_json_server_url();
    let url = format!("{}{}/applist.json", json_server_url, category_id);

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    let mut apps: Vec<AppItem> = response.json().await.map_err(|e| e.to_string())?;

    // 为每个应用设置图标URL
    for app in &mut apps {
        app.icon = Some(format_icon_url(&category_id, &app.pkgname));
        app.category = Some(category_id.clone());
    }

    // 更新缓存
    APPS_CACHE
        .lock()
        .unwrap()
        .insert(category_id.clone(), apps.clone());

    Ok(apps)
}

#[tauri::command]
pub async fn get_all_apps() -> Result<Vec<AppItem>, String> {
    let categories = get_all_categories().await?;
    let futures: Vec<_> = categories
        .iter()
        .map(|category| get_category_apps(category.id.clone()))
        .collect();

    let results = join_all(futures).await;
    let mut all_apps = Vec::new();

    for result in results {
        match result {
            Ok(apps) => all_apps.extend(apps),
            Err(e) => eprintln!("Error fetching apps for category: {}", e),
        }
    }

    Ok(all_apps)
}

#[tauri::command]
pub async fn get_all_categories() -> Result<Vec<Category>, String> {
    // 尝试从缓存中获取数据
    if let Some(cached_categories) = CATEGORIES_CACHE.lock().unwrap().as_ref() {
        return Ok(cached_categories.clone());
    }

    // 如果缓存中没有，从服务器获取数据
    let json_server_url = get_json_server_url();
    let url = format!("{}category.json", json_server_url);

    let client = reqwest::Client::new();
    let response = client
        .get(&url)
        .header("User-Agent", UA)
        .send()
        .await
        .map_err(|e| e.to_string())?;

    let categories: Vec<Category> = response.json().await.map_err(|e| e.to_string())?;

    // 更新缓存
    *CATEGORIES_CACHE.lock().unwrap() = Some(categories.clone());

    Ok(categories)
}
